using System.Collections.Generic;
using Common;
using Entity;
using Mapper;
using TMPro;
using UnityEngine;

namespace CardGameObject.GameScene
{
    public class GameDeck : MonoBehaviour
    {
        public PlayerRoleEnum PlayerRole;
        public TextMeshPro DeckCardCount;

        public GameManager GameManager { get; set; }

        public List<Card> PlayerDeckCardList { get; set; }

        private void Start()
        {
            GameManager = GameManager.GetInstance();
            CardMapper cardMapper = new CardMapper();
            // TODO 修改返回值为CollectCardVO的方法
            PlayerDeckCardList = cardMapper.ListCardByDeckId(1);
            ShuffleDeck();
            cardMapper.CloseConnection();
            UpdateCountText();
        }

        private void UpdateCountText()
        {
            DeckCardCount.text = PlayerDeckCardList.Count.ToString();
        }

        /// <summary>
        /// 打乱玩家牌组中卡牌的顺序
        /// </summary>
        public void ShuffleDeck()
        {
            int n = PlayerDeckCardList.Count;
            System.Random rng = new System.Random();
            while (n > 1)
            {
                n--;
                int k = rng.Next(n + 1);
                Card value = PlayerDeckCardList[k];
                PlayerDeckCardList[k] = PlayerDeckCardList[n];
                PlayerDeckCardList[n] = value;
            }
            Debug.Log($"{PlayerRole}号玩家的卡组进行了洗切");
        }

        public void DrawCards(int count)
        {
            for (int i = 0; i < count; i++)
            {
                if (GameManager != null)
                {
                    // 调用 GameCardManager 中的 createCardOnHandPosition 方法
                    if (PlayerDeckCardList.Count == 0)
                    {
                        if (PlayerRole == PlayerRoleEnum.PLAYER)
                            GameManager.GameEnd(PlayerRoleEnum.AI);
                        else
                            GameManager.GameEnd(PlayerRoleEnum.PLAYER);
                        return;
                    }
                    GameManager.CreateCardOnHandPosition(PlayerRole, PlayerDeckCardList[0]);
                    PlayerDeckCardList.RemoveAt(0);
                    UpdateCountText();
                }
                else
                {
                    Debug.LogError("GameDeck中GameManager为null，检查Start方法代码是否正确！");
                }
            }
        }
    }
}
